//
//  REServerViewController.m
//  录音
//
//  Created by ywy on 2016/12/25.
//  Copyright © 2016年 Wely. All rights reserved.
//

#import "REServerViewController.h"
#import "RETopCollectionViewCell.h" //
#import "RESeverTableViewCell.h" // 服务器的cell
#import "REAlbumName.h" // 三级分类的model
#import "RETrackList.h" // 曲目列表
#import "RECheckLogin.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <MJRefresh/MJRefresh.h>
#import <AVFoundation/AVFoundation.h>
#import "REdateTableViewCell.h" //
#import "RESingleton.h"
#import "HYBCardScaleFlowLayout.h"

struct PlayItemInfo{
    float total;
    float currentTime;
};

@interface REServerViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITableViewDelegate,UITableViewDataSource,AVAudioPlayerDelegate,UIAlertViewDelegate>
// 三级分类的数据源
@property(nonatomic,strong)NSMutableArray * collectionDataArr;
@property(nonatomic,strong)NSMutableArray * tableViewDataArr;
@property(nonatomic,assign) BOOL isSelect;
// 请求的三级分类的id
@property(nonatomic,copy)NSString * thirdIdStr;
@property(nonatomic,assign) BOOL ispaly;
@property(nonatomic,strong) RESeverTableViewCell * baseCell;
@property (nonatomic, strong) NSIndexPath *indexPath;


@property(nonatomic,strong) NSIndexPath * collectionIndexpath;
@property (nonatomic, strong) NSIndexPath *currentPlayingCollectionIndexPath;


@property (nonatomic, strong) AVPlayer     *selfPlayer;
@property (nonatomic, assign) CMTime currentTime;
@property (nonatomic,assign) CGFloat progress;
@property (nonatomic,copy) NSString * progressStr;

@property(nonatomic,assign) BOOL isResh;
@property (nonatomic, strong) id timeObserver;
@property(nonatomic,strong)  HYBCardScaleFlowLayout *layout;

@property(nonatomic,assign) NSInteger  indexRow;

@property(nonatomic,strong) RETrackList * baseModel;


@end

@implementation REServerViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(stopPlayNotiFirsrt) name:@"stopPlayFirst" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(postSucces) name:@"postSucces" object:nil];
}
-(void)postSucces
{
    [self.bottomTableView.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionDataArr = [NSMutableArray new];
    self.tableViewDataArr = [NSMutableArray new];
    self.ispaly = NO;
    self.indexPath = nil;
    self.indexRow = 0;
    self.collectionIndexpath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.currentPlayingCollectionIndexPath = self.collectionIndexpath;
    self.isSelect = YES;
    self.isResh = NO;
    [self creatCollectionView];
    [self creatTableView];
     __weak typeof(self) weakSelf = self;
    self.bottomTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
              [weakSelf creatRequest];
             dispatch_async(dispatch_get_main_queue(), ^{
                 self.indexRow = 0;
                [weakSelf.bottomTableView reloadData];
                [weakSelf.bottomTableView.mj_header endRefreshing];
            });
        });
    }];
    [self.bottomTableView.mj_header beginRefreshing];
}
-(void)creatRequest
{
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary * dict = [NSMutableDictionary new];
    dict[@"cmd"] = @"getAlbum";
    dict[@"uid"]  = [UserDefaults objectForKey:@"userid"];
    [SVProgressHUD showWithStatus:@"获取网络文件中....."];
    [RECheckLogin POST:REBaseUrl parameters:dict progress:^(CGFloat proser) {
    } success:^(id responseObject) {
        if ([responseObject[@"result"] isEqualToString:@"0"]) {
            [weakSelf.collectionDataArr removeAllObjects];
            [SVProgressHUD dismiss];
            for (NSDictionary * dict in responseObject[@"albumList"]) {
                REAlbumName * albumNameModel = [[REAlbumName alloc] init];
                albumNameModel.albumId = dict[@"albumId"];
                 albumNameModel.albumName = dict[@"albumName"];
                 albumNameModel.albumImg = dict[@"albumImg"];
                [weakSelf.collectionDataArr addObject:albumNameModel];
            }
            REAlbumName * albumNameModel = weakSelf.collectionDataArr[0];
            [weakSelf.topCollectionView reloadData];
            weakSelf.thirdIdStr = albumNameModel.albumId;
            [weakSelf requestList:albumNameModel.albumId];
        }else
        {
            [SVProgressHUD showErrorWithStatus:responseObject[@"resultNote"]];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"查看网络!!!!"];
    }];
    
}
-(void)requestList:(NSString *)idStr
{
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary * dict = [NSMutableDictionary new];
    dict[@"cmd"] = @"getAlbumList";
    dict[@"uid"]  = [UserDefaults objectForKey:@"userid"];
    dict[@"thirdTypeId"] = idStr;
        [self.tableViewDataArr removeAllObjects];
       [self.bottomTableView reloadData];
    [RECheckLogin POST:REBaseUrl parameters:dict progress:^(CGFloat proser) {
    } success:^(id responseObject) {
        if ([responseObject[@"result"] isEqualToString:@"0"]) {
            for (NSDictionary * dict in responseObject[@"albumList"]) {
                RETrackList * albumNameModel = [[RETrackList alloc] init];
                albumNameModel.albumId = dict[@"albumId"];
                albumNameModel.albumName = dict[@"albumName"];
                albumNameModel.albumLength = dict[@"albumLength"];
                albumNameModel.albumVoice = dict[@"albumVoice"];
                albumNameModel.praiseCount = dict[@"praiseCount"];
                albumNameModel.commentNum = dict[@"commentNum"];
                [weakSelf.tableViewDataArr addObject:albumNameModel];
            }
            [weakSelf.bottomTableView reloadData];
        }else
        {
            [SVProgressHUD showErrorWithStatus:responseObject[@"resultNote"]];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"查看网络!!!!"];
    }];
}

-(void)creatCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
     // 横向左右间距
    flowLayout.minimumInteritemSpacing = 0;
    // 上线间距
    flowLayout.minimumLineSpacing = 0;

    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
//    self.layout = [[HYBCardScaleFlowLayout alloc] init];
    
    [self.topCollectionView setCollectionViewLayout:flowLayout];
    self.topCollectionView.delegate = self;
    self.topCollectionView.dataSource = self;
    [self.topCollectionView registerNib:[UINib nibWithNibName:@"RETopCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"RETopCollectionViewCell"];
}
#pragma -mark CollectionView DataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.collectionDataArr .count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    RETopCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RETopCollectionViewCell" forIndexPath:indexPath];
    REAlbumName * albumModel = self.collectionDataArr[indexPath.row];
    [cell showData:albumModel];
    cell.collectionCellndex = indexPath;
    return cell;
}
////布局
//-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//    return 20;
//}
//-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
//    return 10;
//}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//     NSIndexPath *ip = [NSIndexPath indexPathForRow:self.indexRow inSection:0];
//    RETopCollectionViewCell * cell = (RETopCollectionViewCell*)[collectionView cellForItemAtIndexPath:ip];
    if (indexPath.row == self.indexRow) {
        return CGSizeMake(160, 100);
        
    }else
    {
        return CGSizeMake(108, 100);
    }
      return CGSizeMake(0, 0);
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.collectionIndexpath = indexPath;
    self.indexRow = indexPath.row;
    
//    RETopCollectionViewCell * cell = (RETopCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
//    NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:0];
//    
//    RETopCollectionViewCell * zeroCell =  (RETopCollectionViewCell*)[collectionView cellForItemAtIndexPath:ip];
//    if (indexPath.row == 0) {
////      self.layout.smallStr = @"big";
//    }else{
////        zeroCell.hiddenImage.hidden = YES;
////       self.layout.smallStr = @"small";
//    }
          [self.topCollectionView reloadData];
    RETrackList * trackListModel = self.collectionDataArr[indexPath.row];
    self.thirdIdStr =  trackListModel.albumId;
    [self requestList:trackListModel.albumId];
}

-(void)creatTableView
{
    self.bottomTableView.delegate =self;
    self.bottomTableView.dataSource = self;
    self.bottomTableView.separatorStyle = 0;
    UIView * footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, REScreenW, 60)];
    self.bottomTableView.tableFooterView =footView;
     // REdateTableViewCell RESeverTableViewCell
    [self.bottomTableView registerNib:[UINib nibWithNibName:@"RESeverTableViewCell" bundle:nil] forCellReuseIdentifier:@"RESeverTableViewCell"];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // self.tableViewDataArr.count
    return self.tableViewDataArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    // REdateTableViewCell RESeverTableViewCell
    RESeverTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"RESeverTableViewCell"];
    cell.selectionStyle = 0;
    RETrackList * model = self.tableViewDataArr[indexPath.row];
    [cell showData:model];
    cell.progressTime.text = @"00:00";
    
    cell.palyButton.selected = (self.collectionIndexpath == self.currentPlayingCollectionIndexPath) ? ([self.indexPath isEqual:indexPath] && self.ispaly) : NO;
    cell.indexPath = indexPath;
    __weak typeof(self) weakSelf = self;
    cell.listBloack = ^(NSInteger tagNumber,RETrackList * baseModel,BOOL playOrStop,UIProgressView *progress,UITableViewCell * baseCell,NSIndexPath * indexPathBlock)
    {
        weakSelf.baseModel = baseModel;
        switch (tagNumber) {
            case 1001:
            {
                //分享
                [SVProgressHUD showErrorWithStatus:@"分享暂时接口没有给出！！"];
            }
                break;
            case 1002:
            {
             // 删除
                UIAlertView * titleAlert = [[UIAlertView alloc] initWithTitle:@"客官不要啊！！" message:@"客官确定要删除？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [titleAlert show];
                
            }
                break;
            case 1003:
            {
                if (!weakSelf.collectionIndexpath) {
                    weakSelf.currentPlayingCollectionIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                } else {
                    weakSelf.currentPlayingCollectionIndexPath = weakSelf.collectionIndexpath;
                }
                weakSelf.baseCell = [weakSelf.bottomTableView cellForRowAtIndexPath:_indexPath];
                [weakSelf palyAndStop:playOrStop withModel:baseModel andIndexPath:indexPath seleCted:_indexPath];
            }
                break;
            default:
                break;
        }
    };
    return cell;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        __weak typeof(self) weakSelf = self;
        NSMutableDictionary * dict = [NSMutableDictionary new];
        dict[@"cmd"] = @"deleteMusic";
        dict[@"uid"] = [UserDefaults objectForKey:@"userid"];
        dict[@"albumId"]  = weakSelf.baseModel.albumId;
        [SVProgressHUD showWithStatus:@"删除曲目中....."];
        [RECheckLogin POST:REBaseUrl parameters:dict progress:^(CGFloat prosser) {
        } success:^(id responseObject) {
            if ([responseObject[@"result"] isEqualToString:@"0"]) {
                [SVProgressHUD showSuccessWithStatus:responseObject[@"resultNote"]];
                [weakSelf.bottomTableView reloadData];
                [weakSelf requestList:weakSelf.thirdIdStr];
                [weakSelf creatRequest];
//                [weakSelf.topCollectionView reloadData];
                if ( [[RESingleton defaultCent] isNotUP:responseObject[@"localId"]] == YES) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"Update" object:self userInfo:nil];
                }
            }else
            {
                [SVProgressHUD showErrorWithStatus:responseObject[@"resultNote"]];
            }
            [SVProgressHUD dismiss];
        } failure:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"查看网络!!"];
        }];
    }
}



-(void)palyAndStop:(BOOL)playOrStop  withModel:(RETrackList*)baseModel andIndexPath:(NSIndexPath*)indexPath seleCted:(NSIndexPath*)indexPathOfBlock
{
    if (![self.indexPath isEqual:indexPath]){
        [self initPalyerWithModel:baseModel];
    }else{
        if (!self.ispaly) {
            RESeverTableViewCell * cell = [self.bottomTableView cellForRowAtIndexPath:indexPath];
            if (cell.progress.progress <= 0) {
                [self.selfPlayer seekToTime:CMTimeMake(0, 1)];
            }
            [self.selfPlayer play];
            
            self.ispaly = YES;
        }else{
            [self.selfPlayer pause];
            self.ispaly = NO;
        }
    }
    
    self.indexPath = indexPath;
    [self.bottomTableView reloadData];
}


-(void)initPalyerWithModel:(RETrackList*)baseModel{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [self.selfPlayer.currentItem removeObserver:self  forKeyPath:@"status"];
    [self.selfPlayer removeTimeObserver:self.timeObserver];

    AVAudioSession *session = [AVAudioSession sharedInstance];
      [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
//    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    NSURL  * baseUrl = [NSURL URLWithString:[baseModel.albumVoice stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    AVURLAsset *localAssert = [[AVURLAsset alloc]initWithURL:baseUrl options:nil];
    //AVPlayerItem 他是对assert对应资源的一种整体描述，包括能够播放，以及影片长度等内容
    AVPlayerItem * item = [[AVPlayerItem alloc]initWithAsset:localAssert];
    if(self.selfPlayer){
        [self.selfPlayer pause];
        self.selfPlayer = nil;
    }
    self.selfPlayer = [AVPlayer playerWithPlayerItem:item];
    //监听AVPlayerItem的status状态，当status状态为readyToPlayer时，我们认为影片时可以播放的
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:self.selfPlayer.currentItem];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    __weak typeof(self) weakSelf = self;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *item = (AVPlayerItem*)object;
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            //这里影片可以播放
            [self.selfPlayer play];
            self.ispaly = YES;
       weakSelf.timeObserver  =    [weakSelf.selfPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
                //time是指当前影片播放的时间
                //得到影片的总时间
                CMTime totalTime = weakSelf.selfPlayer.currentItem.duration;
                //CMTimeGetSeconds 把CMTime转换为秒数
                CGFloat currentTimeSeconds = CMTimeGetSeconds(time);
                CGFloat totalSeconds = CMTimeGetSeconds(totalTime);
                int  minnute = currentTimeSeconds/60;
                int second = currentTimeSeconds-minnute*60;
                if (weakSelf.currentPlayingCollectionIndexPath == weakSelf.collectionIndexpath) {
                    RESeverTableViewCell * cell = [weakSelf.bottomTableView cellForRowAtIndexPath:weakSelf.indexPath];
                    weakSelf.progressStr = [NSString stringWithFormat:@"%02d:%02d",minnute,second];
                    weakSelf.progress = currentTimeSeconds*1.0/totalSeconds;
                    if (cell){
                        
                        cell.progressTime.text = weakSelf.progressStr;
                        [cell.progress setProgress:weakSelf.progress animated:NO];
                        
                    }
                } else {
                    
                }
            }];
            [self.bottomTableView reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器文件暂时无法播放"];
        }
    }
}
-(void)playbackFinished{
    RESeverTableViewCell* cell = [self.bottomTableView cellForRowAtIndexPath:self.indexPath];
    
    if (cell){
        cell.progress.progress = 0.0;
        cell.progressTime.text = @"00:00";
        self.progress = 0.0;
        self.progressStr = @"00:00";
        [cell.palyButton setSelected:NO];
    }
    self.ispaly = NO;
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"postSucces" object:nil];
      [[NSNotificationCenter defaultCenter] removeObserver:self name:@"stopPlayFirst" object:nil];
    if (self.selfPlayer) {
        REdateTableViewCell * cell = [self.bottomTableView cellForRowAtIndexPath:self.indexPath];
        self.ispaly = NO;
        [cell.palyButton setSelected:NO];
        [self.selfPlayer pause];
    }
}
-(void)stopPlayNoti
{
    if (self.selfPlayer) {
        REdateTableViewCell * cell = [self.bottomTableView cellForRowAtIndexPath:self.indexPath];
        self.ispaly = NO;
        [cell.palyButton setSelected:NO];
        [self.selfPlayer pause];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"stopPlayNoti" object:nil];
}
-(void)stopPlayNotiFirsrt
{
    if (self.selfPlayer) {
        REdateTableViewCell * cell = [self.bottomTableView cellForRowAtIndexPath:self.indexPath];
        self.ispaly = NO;
        [cell.palyButton setSelected:NO];
        [self.selfPlayer pause];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"stopPlayNotiFirsrt" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
